package com.clay.appointment.common.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clay.appointment.common.annotation.TableHead;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 分页信息
 *
 * @author Yeung Wah
 * @since 2021/7/9
 */
@Data
public class PageInfo<T> {

    @ApiParam("总数")
    private long total;
    @ApiParam("页号")
    private long pageNumber;
    @ApiParam("每页条数")
    private long pageSize;
    @ApiParam("对象集合")
    private List<T> rows;
    @ApiParam("页面信息")
    private List<TableInfo> tableInfo;

    /**
     * 私有构造 只能通过build方法构建
     */
    private PageInfo(long total, long pageNumber, long pageSize, List<T> rows, List<TableInfo> tableInfo) {
        this.total = total;
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        this.rows = rows;
        this.tableInfo = tableInfo;
    }

    /**
     * 页面table信息
     */
    @Data
    @AllArgsConstructor
    private static class TableInfo {
        private String headers;
        private String fields;
    }

    /**
     * 构建不含有表头的分页信息
     *
     * @param page page
     * @return 分页信息
     */
    public static <T> PageInfo<T> buildPage(Page<T> page) {
        return new PageInfo<>(page.getTotal(), page.getCurrent(), page.getSize(), page.getRecords(), null);
    }

    /**
     * 构建含有表头的分页信息
     *
     * @param page  page
     * @param clazz 数据类型字节码
     * @return 分页信息
     */
    public static <T> PageInfo<T> buildPage(Page<T> page, Class<T> clazz) {
        List<TableInfo> tableInfo = new ArrayList<>();

        //通过反射获取表头
        for (Field field : clazz.getDeclaredFields()) {
            TableHead tableHead = field.getAnnotation(TableHead.class);
            if (Objects.nonNull(tableHead)) {
                tableInfo.add(new TableInfo(tableHead.value(), field.getName()));
            }
        }

        return new PageInfo<>(page.getTotal(), page.getCurrent(), page.getSize(), page.getRecords(), tableInfo);
    }


    /**
     * 构建含有表头的分页信息
     *
     * @param page  page
     * @param clazz 数据类型字节码
     * @return 分页信息
     */
    public static <T> PageInfo<T> buildPage(org.springframework.data.domain.Page<T> page, Class<T> clazz) {
        List<TableInfo> tableInfo = new ArrayList<>();

        //通过反射获取表头
        for (Field field : clazz.getDeclaredFields()) {
            TableHead tableHead = field.getAnnotation(TableHead.class);
            if (Objects.nonNull(tableHead)) {
                tableInfo.add(new TableInfo(tableHead.value(), field.getName()));
            }
        }
        return new PageInfo<>(page.getTotalElements(),page.getNumber(),page.getSize(),page.getContent(),tableInfo);
    }


}